"""医学知识库配置文件
基于BASP分型法和专业脱发诊断标准
"""

from typing import Dict, List, Any
from enum import Enum

class BASPType(Enum):
    """BASP分型枚举"""
    # 基本型 (Basic)
    L0 = "L0"  # 发际线正常，无后移
    M0 = "M0"  # 前额发际线保留，无脱发
    M1 = "M1"  # 两侧发际线后退未超过原处至头顶前1/3
    M2 = "M2"  # 两侧发际线后退未超过原处至头顶中1/3
    M3 = "M3"  # 两侧发际线后退达到原处至头顶后1/3
    C0 = "C0"  # 前额发际线保留，无脱发
    C1 = "C1"  # 前额发际线中部后退前1/3范围内
    C2 = "C2"  # 前额发际线中部后退前中1/3范围内
    C3 = "C3"  # 前额发际线中部后退前后1/3范围内
    U1 = "U1"  # 发际线后退头顶至枕突前1/3范围内
    U2 = "U2"  # 发际线后退头顶至枕突中1/3范围内
    U3 = "U3"  # 发际线后退头顶至枕突后1/3范围内
    
    # 特殊型 (Specific)
    V1 = "V1"  # 轻度，头顶部头发密度可见降低
    V2 = "V2"  # 中度，头顶部头发密度明显降低
    V3 = "V3"  # 重度，头顶部头发非常稀少或缺失
    F1 = "F1"  # 轻度，前额区头发密度可见降低
    F2 = "F2"  # 中度，前额区头发密度明显降低
    F3 = "F3"  # 重度，前额区头发非常稀少或缺失

class MedicalKnowledgeBase:
    """医学知识库类"""
    
    # BASP分型详细描述
    BASP_DESCRIPTIONS = {
        "L0": {
            "name": "L型正常",
            "description": "发际线正常，无后移，表示毛发正常",
            "severity": "正常",
            "characteristics": ["发际线完整", "无明显脱发迹象", "头发密度正常"],
            "treatment_difficulty": "无需治疗",
            "prognosis": "优秀"
        },
        "M1": {
            "name": "M型轻度",
            "description": "两侧发际线后退未超过原处至头顶前1/3",
            "severity": "轻度",
            "characteristics": ["两鬓角轻微后退", "M型轮廓初现", "整体密度尚可"],
            "treatment_difficulty": "较易治疗",
            "prognosis": "良好"
        },
        "M2": {
            "name": "M型中度",
            "description": "两侧发际线后退未超过原处至头顶中1/3",
            "severity": "中度",
            "characteristics": ["M型轮廓明显", "两鬓角明显后退", "前额区域扩大"],
            "treatment_difficulty": "中等难度",
            "prognosis": "一般"
        },
        "M3": {
            "name": "M型重度",
            "description": "两侧发际线后退达到原处至头顶后1/3",
            "severity": "重度",
            "characteristics": ["M型轮廓深刻", "大面积发际线后退", "前额显著暴露"],
            "treatment_difficulty": "治疗困难",
            "prognosis": "较差"
        },
        "C1": {
            "name": "C型轻度",
            "description": "前额发际线中部后退前1/3范围内",
            "severity": "轻度",
            "characteristics": ["前额中部轻微后退", "C型弧度初现", "两侧相对完整"],
            "treatment_difficulty": "较易治疗",
            "prognosis": "良好"
        },
        "C2": {
            "name": "C型中度",
            "description": "前额发际线中部后退前中1/3范围内",
            "severity": "中度",
            "characteristics": ["C型弧度明显", "前额中部明显后退", "发际线呈半圆形"],
            "treatment_difficulty": "中等难度",
            "prognosis": "一般"
        },
        "C3": {
            "name": "C型重度",
            "description": "前额发际线中部后退前后1/3范围内",
            "severity": "重度",
            "characteristics": ["深度C型弧度", "大面积前额暴露", "发际线大幅后退"],
            "treatment_difficulty": "治疗困难",
            "prognosis": "较差"
        },
        "U1": {
            "name": "U型轻度",
            "description": "发际线后退头顶至枕突前1/3范围内",
            "severity": "重度",
            "characteristics": ["马蹄形脱发初现", "顶部开始稀疏", "U型轮廓形成"],
            "treatment_difficulty": "治疗困难",
            "prognosis": "较差"
        },
        "U2": {
            "name": "U型中度",
            "description": "发际线后退头顶至枕突中1/3范围内",
            "severity": "重度",
            "characteristics": ["明显马蹄形脱发", "大面积头顶暴露", "U型轮廓清晰"],
            "treatment_difficulty": "极难治疗",
            "prognosis": "差"
        },
        "U3": {
            "name": "U型重度",
            "description": "发际线后退头顶至枕突后1/3范围内",
            "severity": "极重度",
            "characteristics": ["严重马蹄形脱发", "几乎全秃", "仅后枕部有发"],
            "treatment_difficulty": "药物无效",
            "prognosis": "极差"
        },
        "V1": {
            "name": "V型轻度(地中海型)",
            "description": "轻度，头顶部头发密度可见降低",
            "severity": "轻度",
            "characteristics": ["头顶密度轻微下降", "发旋区域稀疏", "整体轮廓尚可"],
            "treatment_difficulty": "较易治疗",
            "prognosis": "良好"
        },
        "V2": {
            "name": "V型中度(地中海型)",
            "description": "中度，头顶部头发密度明显降低",
            "severity": "中度",
            "characteristics": ["头顶明显稀疏", "地中海轮廓显现", "头皮可见"],
            "treatment_difficulty": "中等难度",
            "prognosis": "一般"
        },
        "V3": {
            "name": "V型重度(地中海型)",
            "description": "重度，头顶部头发非常稀少或缺失",
            "severity": "重度",
            "characteristics": ["头顶大面积缺失", "典型地中海型", "头皮完全暴露"],
            "treatment_difficulty": "治疗困难",
            "prognosis": "较差"
        },
        "F1": {
            "name": "F型轻度(女性型)",
            "description": "轻度，前额区头发密度可见降低",
            "severity": "轻度",
            "characteristics": ["弥漫性稀疏", "前额区密度下降", "整体变细"],
            "treatment_difficulty": "较易治疗",
            "prognosis": "良好"
        },
        "F2": {
            "name": "F型中度(女性型)",
            "description": "中度，前额区头发密度明显降低",
            "severity": "中度",
            "characteristics": ["明显弥漫性稀疏", "前额区显著变薄", "分缝线变宽"],
            "treatment_difficulty": "中等难度",
            "prognosis": "一般"
        },
        "F3": {
            "name": "F型重度(女性型)",
            "description": "重度，前额区头发非常稀少或缺失",
            "severity": "重度",
            "characteristics": ["严重弥漫性脱发", "前额区大面积稀疏", "头皮明显可见"],
            "treatment_difficulty": "治疗困难",
            "prognosis": "较差"
        }
    }
    
    # 检测关键特征
    DETECTION_FEATURES = {
        "hairline_patterns": {
            "M_shape": ["两鬓角后退", "M型轮廓", "额颞角脱发"],
            "C_shape": ["前额中部后退", "半圆形发际线", "C型弧度"],
            "U_shape": ["马蹄形脱发", "大面积后退", "顶部连通"],
            "normal": ["发际线完整", "无明显后退", "轮廓自然"]
        },
        "density_levels": {
            "normal": "密度正常，无明显稀疏",
            "mild_thinning": "轻度稀疏，密度略有下降",
            "moderate_thinning": "中度稀疏，密度明显下降",
            "severe_thinning": "重度稀疏，大面积缺失",
            "bald": "完全脱发，头皮暴露"
        },
        "scalp_visibility": {
            "not_visible": "头皮不可见",
            "slightly_visible": "头皮轻微可见",
            "clearly_visible": "头皮清晰可见",
            "fully_exposed": "头皮完全暴露"
        }
    }
    
    # 护理建议模板
    CARE_SUGGESTIONS = {
        "正常": [
            "保持健康的生活方式和均衡饮食",
            "定期使用温和的洗发产品",
            "避免过度拉扯和化学处理",
            "定期头皮按摩促进血液循环"
        ],
        "轻度": [
            "及早采取预防措施，避免脱发加重",
            "使用温和的防脱洗发水",
            "补充维生素B、铁、锌等营养素",
            "减少压力，保证充足睡眠",
            "避免频繁烫染和紧束发型"
        ],
        "中度": [
            "建议咨询专业皮肤科医生",
            "考虑使用医用级防脱产品",
            "调整生活方式，减少熬夜和压力",
            "增加蛋白质和维生素摄入",
            "定期进行头皮护理和按摩"
        ],
        "重度": [
            "强烈建议就医进行专业诊断",
            "可能需要考虑医学治疗方案",
            "保持积极心态，避免过度焦虑",
            "使用专业的头皮护理产品",
            "如有需要可咨询植发等治疗选项"
        ],
        "极重度": [
            "必须寻求专业医疗帮助",
            "药物治疗效果有限，需综合评估",
            "可考虑植发手术等医疗干预",
            "重视心理健康和社会支持",
            "使用假发等辅助手段改善外观"
        ]
    }
    
    @classmethod
    def get_basp_info(cls, basp_type: str) -> Dict[str, Any]:
        """获取BASP分型详细信息"""
        return cls.BASP_DESCRIPTIONS.get(basp_type, {})
    
    @classmethod
    def get_care_suggestions(cls, severity: str) -> List[str]:
        """根据严重程度获取护理建议"""
        return cls.CARE_SUGGESTIONS.get(severity, cls.CARE_SUGGESTIONS["轻度"])
    
    @classmethod
    def generate_professional_prompt(cls) -> str:
        """生成包含专业医学知识的检测prompt"""
        basp_knowledge = """
        BASP分型法是目前临床使用最多的雄激素性秃发分级方法，由北京大学人民医院皮肤科提出。
        该分型法根据发际线形态、额部与顶部头发密度进行分级，包括：
        
        【基本型 (Basic)】：
        - L型：发际线正常，无后移
        - M型：从发际线两额颞角开始脱发，呈M字形（M0-M3级）
        - C型：前额发际线中部后缩，呈半圆形C字形（C0-C3级）
        - U型：发际线退至头顶后，呈马蹄形U字形（U1-U3级）
        
        【特殊型 (Specific)】：
        - V型：头顶部头发稀疏，俗称"地中海"型（V1-V3级）
        - F型：头发密度弥漫性降低，前额区显著，常见于女性（F1-F3级）
        """
        
        detection_guidelines = """
        【检测要点】：
        1. 发际线形态：观察是否呈M、C、U型后退
        2. 头发密度：评估不同区域的密度变化
        3. 头皮可见度：判断头皮暴露程度
        4. 脱发模式：识别男性型、女性型或其他模式
        5. 严重程度：根据面积和密度综合评估
        """
        
        return basp_knowledge + detection_guidelines
    
    @classmethod
    def validate_detection_result(cls, result: Dict[str, Any]) -> bool:
        """验证检测结果的合理性"""
        required_fields = ["baspType", "severity", "description", "suggestion", "confidence"]
        
        # 检查必需字段
        for field in required_fields:
            if field not in result:
                return False
        
        # 验证BASP分型是否有效
        basp_type = result.get("baspType", "")
        if basp_type not in cls.BASP_DESCRIPTIONS:
            return False
        
        # 验证置信度范围
        confidence = result.get("confidence", 0)
        if not isinstance(confidence, (int, float)) or not (0 <= confidence <= 1):
            return False
        
        return True
    
    @classmethod
    def enhance_result_with_knowledge(cls, result: Dict[str, Any]) -> Dict[str, Any]:
        """使用医学知识增强检测结果"""
        basp_type = result.get("baspType", "")
        basp_info = cls.get_basp_info(basp_type)
        
        if basp_info:
            # 增强描述信息
            result["medicalName"] = basp_info.get("name", "")
            result["characteristics"] = basp_info.get("characteristics", [])
            result["treatmentDifficulty"] = basp_info.get("treatment_difficulty", "")
            result["prognosis"] = basp_info.get("prognosis", "")
            
            # 根据严重程度提供专业建议
            severity = basp_info.get("severity", "轻度")
            professional_suggestions = cls.get_care_suggestions(severity)
            result["professionalSuggestions"] = professional_suggestions
        
        return result